package dtu.app.fragment;

import java.util.List;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.iqengines.demo.R;

import dtu.app.listadapter.ProductArrayAdapter;
import dtu.app.listloader.ProductListLoader;
import dtu.app.model.Product;

public class ProductListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<List<Product>> {

	ProductArrayAdapter mAdapter;
	
	@Override public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		System.out.println("DataListFragment.onActivityCreated");

		// Initially there is no data 
		setEmptyText("No Data Here");

		// Create an empty adapter we will use to display the loaded data.
		mAdapter = new ProductArrayAdapter(getActivity());
		setListAdapter(mAdapter);

		// Start out with a progress indicator.
		setListShown(false);

		// Prepare the loader.  Either re-connect with an existing one,
		// or start a new one.
		getLoaderManager().initLoader(0, null, this);
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		// Insert desired behavior here.  	        			
		Log.i("DataListFragment", "Item clicked: " + id);
		((TextView) v.findViewById(R.id.product_total)).setText("Jeppe");
	}

	@Override
	public Loader<List<Product>> onCreateLoader(int arg0, Bundle bundle) {
		Log.i("DataListFragment", "DataListFragment.onCreateLoader");
		return new ProductListLoader(getActivity(), bundle);
	}

	@Override
	public void onLoadFinished(Loader<List<Product>> arg0, List<Product> data) {
		mAdapter.setData(data);
		Log.i("DataListFragment", "DataListFragment.onLoadFinished");

		// The list should now be shown.
		if (isResumed()) {
			setListShown(true);
		} else {
			setListShownNoAnimation(true);
		}
	}

	@Override
	public void onLoaderReset(Loader<List<Product>> arg0) {
		mAdapter.setData(null);
	}

	public void updateList(String category) {	
		Log.i("DataListFragment", "updateList");
		Bundle b = new Bundle();
		b.putString("category", category);
		getLoaderManager().restartLoader(0, b, this);
	}
	
}